package mspbots.data.tl.prod.autotask.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultEntity;
import mspbots.data.tl.prod.autotask.mapper.TaskAutotaskInformationMapper;
import mspbots.data.tl.prod.autotask.mapper.TaskAutotaskOpportunityMapper;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskInformation;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskOpportunity;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskTicket;
import mspbots.data.tl.prod.autotask.service.TaskAutotaskOpportunityService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@Log4j2
@RequiredArgsConstructor
@DS("master")
public class TaskAutotaskOpportunityServiceImpl extends AbstractBaseServiceImpl<TaskAutotaskOpportunityMapper, TaskAutotaskOpportunity>
        implements TaskAutotaskOpportunityService {
    private final TaskAutotaskInformationMapper taskAutotaskInformationMapper;

    @Override
    public void sync(ResultEntity content) {
        log.debug("Auto task opportunity receiver content {}", content);
        JsonNode entity = content.getEntity();
        TaskAutotaskOpportunity data = TaskAutotaskOpportunity.builder()
                .opportunityId(super.getLongValue(entity.get("id")))
                .advancedField1(ObjectUtils.isEmpty(entity.get("advancedField1")) ? null : entity.get("advancedField1").asDouble())
                .advancedField2(ObjectUtils.isEmpty(entity.get("advancedField2")) ? null : entity.get("advancedField2").asDouble())
                .advancedField3(ObjectUtils.isEmpty(entity.get("advancedField3")) ? null : entity.get("advancedField3").asDouble())
                .advancedField4(ObjectUtils.isEmpty(entity.get("advancedField4")) ? null : entity.get("advancedField4").asDouble())
                .advancedField5(ObjectUtils.isEmpty(entity.get("advancedField5")) ? null : entity.get("advancedField5").asDouble())
                .amount(ObjectUtils.isEmpty(entity.get("amount")) ? null : entity.get("amount").asDouble())
                .assessmentScore(ObjectUtils.isEmpty(entity.get("assessmentScore")) ? null : entity.get("assessmentScore").asDouble())
                .cost(ObjectUtils.isEmpty(entity.get("cost")) ? null : entity.get("cost").asDouble())
                .monthlyCost(ObjectUtils.isEmpty(entity.get("monthlyCost")) ? null : entity.get("monthlyCost").asDouble())
                .monthlyRevenue(ObjectUtils.isEmpty(entity.get("monthlyRevenue")) ? null : entity.get("monthlyRevenue").asDouble())
                .onetimeCost(ObjectUtils.isEmpty(entity.get("onetimeCost")) ? null : entity.get("onetimeCost").asDouble())
                .onetimeRevenue(ObjectUtils.isEmpty(entity.get("onetimeRevenue")) ? null : entity.get("onetimeRevenue").asDouble())
                .quarterlyCost(ObjectUtils.isEmpty(entity.get("quarterlyCost")) ? null : entity.get("quarterlyCost").asDouble())
                .quarterlyRevenue(ObjectUtils.isEmpty(entity.get("quarterlyRevenue")) ? null : entity.get("quarterlyRevenue").asDouble())
                .relationshipAssessmentScore(ObjectUtils.isEmpty(entity.get("relationshipAssessmentScore")) ? null : entity.get("relationshipAssessmentScore").asDouble())
                .semiannualCost(ObjectUtils.isEmpty(entity.get("semiannualCost")) ? null : entity.get("semiannualCost").asDouble())
                .semiannualRevenue(ObjectUtils.isEmpty(entity.get("semiannualRevenue")) ? null : entity.get("semiannualRevenue").asDouble())
                .technicalAssessmentScore(ObjectUtils.isEmpty(entity.get("technicalAssessmentScore")) ? null : entity.get("technicalAssessmentScore").asDouble())
                .yearlyCost(ObjectUtils.isEmpty(entity.get("yearlyCost")) ? null : entity.get("yearlyCost").asDouble())
                .yearlyRevenue(ObjectUtils.isEmpty(entity.get("yearlyRevenue")) ? null : entity.get("yearlyRevenue").asDouble())
                .barriers(ObjectUtils.isEmpty(entity.get("barriers")) ? null : entity.get("barriers").asText())
                .helpNeeded(ObjectUtils.isEmpty(entity.get("helpNeeded")) ? null : entity.get("helpNeeded").asText())
                .lossReasonDetail(ObjectUtils.isEmpty(entity.get("lossReasonDetail")) ? null : entity.get("lossReasonDetail").asText())
                .market(ObjectUtils.isEmpty(entity.get("market")) ? null : entity.get("market").asText())
                .nextStep(ObjectUtils.isEmpty(entity.get("nextStep")) ? null : entity.get("nextStep").asText())
                .promotionName(ObjectUtils.isEmpty(entity.get("promotionName")) ? null : entity.get("promotionName").asText())
                .revenueSpreadUnit(ObjectUtils.isEmpty(entity.get("revenueSpreadUnit")) ? null : entity.get("revenueSpreadUnit").asText())
                .title(ObjectUtils.isEmpty(entity.get("title")) ? null : entity.get("title").asText())
                .winReasonDetail(ObjectUtils.isEmpty(entity.get("winReasonDetail")) ? null : entity.get("winReasonDetail").asText())
                .lossReason(ObjectUtils.isEmpty(entity.get("lossReason")) ? null : entity.get("lossReason").asInt())
                .probability(ObjectUtils.isEmpty(entity.get("probability")) ? null : entity.get("probability").asInt())
                .productId(ObjectUtils.isEmpty(entity.get("productId")) ? null : entity.get("productId").asInt())
                .rating(ObjectUtils.isEmpty(entity.get("rating")) ? null : entity.get("rating").asInt())
                .revenueSpread(ObjectUtils.isEmpty(entity.get("revenueSpread")) ? null : entity.get("revenueSpread").asInt())
                .salesProcessPercentComplete(ObjectUtils.isEmpty(entity.get("salesProcessPercentComplete")) ? null : entity.get("salesProcessPercentComplete").asInt())
                .stage(ObjectUtils.isEmpty(entity.get("stage")) ? null : entity.get("stage").asInt())
                .status(ObjectUtils.isEmpty(entity.get("status")) ? null : entity.get("status").asInt())
                .totalAmountMonths(ObjectUtils.isEmpty(entity.get("totalAmountMonths")) ? null : entity.get("totalAmountMonths").asInt())
                .winReason(ObjectUtils.isEmpty(entity.get("winReason")) ? null : entity.get("winReason").asInt())
                .ownerResourceId(super.getLongValue(entity.get("ownerResourceID")))
                .useQuoteTotals(ObjectUtils.isEmpty(entity.get("useQuoteTotals")) ? null : entity.get("useQuoteTotals").asBoolean())
                .closedDate(super.getDateTimeValue(entity.get("closedDate")))
                .createDate(super.getDateTimeValue(entity.get("createDate")))
                .lastActivity(super.getDateTimeValue(entity.get("lastActivity")))
                .projectedCloseDate(super.getDateTimeValue(entity.get("projectedCloseDate")))
                .throughDate(super.getDateTimeValue(entity.get("throughDate")) )
                .syncTime(LocalDateTime.now())
                .build();
        data.setTenantCode(content.getTenantId());
        setNameInfo(data);

        TaskAutotaskOpportunity dbData = super.baseMapper.selectOne(Wrappers.<TaskAutotaskOpportunity>lambdaQuery()
                .eq(TaskAutotaskOpportunity::getTenantCode, data.getTenantCode())
                .eq(TaskAutotaskOpportunity::getOpportunityId, data.getOpportunityId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)) {
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }
    }

    private void setNameInfo(TaskAutotaskOpportunity data) {
        List<TaskAutotaskInformation> informationList = taskAutotaskInformationMapper.selectList(Wrappers.<TaskAutotaskInformation>lambdaQuery()
                .eq(TaskAutotaskInformation::getTenantCode, data.getTenantCode())
                .eq(TaskAutotaskInformation::getType,"Opportunities")
                .in(TaskAutotaskInformation::getName, List.of("Status", "Stage")));
        if (!CollectionUtils.isEmpty(informationList)) {
            informationList.forEach(information -> {
                if (!ObjectUtils.isEmpty(data.getStatus())
                        && "Status".equalsIgnoreCase(information.getName())
                        && data.getStatus().toString().equals(information.getValue())) {
                    data.setStatusName(information.getLabel());
                } else if (!ObjectUtils.isEmpty(data.getStage())
                        && "Stage".equalsIgnoreCase(information.getName())
                        && data.getStage().toString().equals(information.getValue())) {
                    data.setStageName(information.getLabel());
                }
            });
        }
    }

   /* private String getStatusName(Long tenant_code,Integer status){
        TaskAutotaskInformation information=taskAutotaskInformationMapper.selectOne(Wrappers.<TaskAutotaskInformation>lambdaQuery()
                .eq(TaskAutotaskInformation::getTenantCode,tenant_code)
                .eq(TaskAutotaskInformation::getType,"Opportunities")
                .eq(TaskAutotaskInformation::getName,"Status")
                .eq(TaskAutotaskInformation::getValue,String.valueOf(status))
                .last("limit 1"));
        if (!ObjectUtils.isEmpty(information)){
            return information.getLabel();
        }
        return null;
    }*/

}